package com.hispeed.management.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by wangtt on 2017-5-11.
 */
public class MD5 {

    private static Logger logger = LoggerFactory.getLogger(MD5.class);

    /**
     * MD5加密算法
     * @param strSrc 待加密的字符串
     * @return 加密后的字符串
     * @throws NoSuchAlgorithmException 没有这种产生消息摘要的方法
     * @throws UnsupportedEncodingException
     */
    public final static String EncoderByMd5(String strSrc) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F' };

        char str[] = null;

        try
        {
            byte[] strTemp = strSrc.getBytes("UTF-8");
            logger.debug("编码格式是：UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return new String(str);

    }


    /**
     * 判断用户密码是否正确
     * @param password1 用户输入的密码
     * @param password2 数据库中存储的密码 --用户密码的摘要
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static boolean checkPwd(String password1,String password2){
        try{
            System.out.println(EncoderByMd5(password1));
            if(EncoderByMd5(password1).equals(password2))
                return true;
            else
                return false;
        } catch(Exception e){
            logger.error("EncoderByMd5 catch Exception:"+e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
